﻿using GalaSoft.MvvmLight;
using wp7cinema.Model;
using System.Collections.Generic;
using System.Net;
using System;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight.Command;
using wp7cinema.ExtendedMethod;
using Microsoft.Phone.Controls;
using System.Windows;
using System.Text.RegularExpressions;

namespace wp7cinema.ViewModel
{
    public class TheaterInfoViewModel : ViewModelBase
    {
        MovieItem selectedMovie;
        IEnumerable<MovieItem> allMovies;
        EnableDate selectedDate;

        #region 바인딩될 데이터들..
        private TheaterItem _selectedTheater;
        public TheaterItem SelectedTheater
        {
            get { return _selectedTheater; }
            set
            {
                _selectedTheater = value;
                RaisePropertyChanged("SelectedTheater");
            }
        }

        private IEnumerable<MovieItem> _movies;
        public IEnumerable<MovieItem> Movies
        {
            get { return _movies; }
            set
            {
                _movies = value;
                RaisePropertyChanged("Movies");
            }
        }

        private List<EnableDate> _enableDates;
        public List<EnableDate> EnableDates
        {
            get { return _enableDates; }
            set
            {
                _enableDates = value;
                RaisePropertyChanged("EnableDates");
            }
        }

        private IEnumerable<TicketInfo> _tickets;
        public IEnumerable<TicketInfo> Tickets
        {
            get { return _tickets; }
            set
            {
                _tickets = value;
                RaisePropertyChanged("Tickets");
            }
        }
        #endregion

        #region Command 들...

        #region ListPicker 버그로 임시(?)수정
        //public RelayCommand<MovieItem> SetMovieCommand { get; set; }
        public void SetMovieCommandExecute(MovieItem movie)
        {
            if (movie == null) return;
            selectedMovie = movie;
            getEnableDate(movie.Key);
        }

        public void SetDateCommandExecute(EnableDate date)
        {
            if (date == null) return;
            selectedDate = date;
            getTime(selectedMovie.Key, date.Key);
        }
        #endregion

        public RelayCommand<ListPicker> SetMovieCommand { get; set; }
        public void SetMovieCommandExecute(ListPicker listPicker)
        {
            MovieItem movie = listPicker.SelectedItem as MovieItem;
            SetMovieCommandExecute(movie);
        }

        public RelayCommand<ListPicker> SetDateCommand { get; set; }
        public void SetDateCommandExecute(ListPicker listPicker)
        {
            EnableDate date = listPicker.SelectedItem as EnableDate;
            SetDateCommandExecute(date);
        }

        public RelayCommand<TicketInfo> SetTicketInfo { get; set; }
        public void SetTicketInfoExecute(TicketInfo info)
        {
            if (info == null) return;
            string url = "http://movie.naver.com/movie/reservation/ticketingInfo2.nhn?movie="
                + selectedMovie.Key + "&theater=" + SelectedTheater.Key + "&date=" + selectedDate + "&time=" + info.Time + "&seats=1&hall=" + info.ID;
            WebClient client = new WebClient();
            client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
            client.DownloadStringAsync(new Uri(url));
        }
        void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            string xmlStr = e.Result.Replace("&", "");
            XDocument xdoc = XDocument.Parse(xmlStr);
            string seats = xdoc.Root.Element("ticket").Attribute("seats").Value;
            MessageBox.Show("잔여좌석 : " + seats);
        }
        #endregion

        #region 생성자

        public TheaterInfoViewModel()
        {
            //SetMovieCommand = new RelayCommand<MovieItem>(SetMovieCommandExecute);
            //SetSubRegionCommand = new RelayCommand<Region>(SetSubRegionCommandExecute);
            //SetTheatersCommand = new RelayCommand<SubRegion>(SetTheatersCommandExecute);
            //SetTheaterCommand = new RelayCommand<TheaterItem>(SetTheaterCommandExecute);
            SetMovieCommand = new RelayCommand<ListPicker>(SetMovieCommandExecute);
            SetDateCommand = new RelayCommand<ListPicker>(SetDateCommandExecute);
            SetTicketInfo = new RelayCommand<TicketInfo>(SetTicketInfoExecute);

            if (IsInDesignMode)
            {
                #region 디자인용 더미데이터
                Movies = new ObservableCollection<MovieItem> {
                    new MovieItem { Title = "아저씨" },
                    new MovieItem { Title = "아저씨(3D)" },
                    new MovieItem { Title = "아저씨(4bit)" },
                    new MovieItem { Title = "아저씨(디지털)" }
                };
                EnableDates = new List<EnableDate> {
                    new EnableDate { Key="20100822", Value="08월 22일 금요일" }
                };
                Tickets = new ObservableCollection<TicketInfo> {
                    new TicketInfo { ViewStr = "1관 13 : 20" },
                    new TicketInfo { ViewStr = "1관 13 : 20" },
                    new TicketInfo { ViewStr = "1관 13 : 20" },
                    new TicketInfo { ViewStr = "1관 13 : 20" }
                };
                SelectedTheater = new TheaterItem { Name = "전대 씨너스" };
                #endregion
            }
            else
            {
                #region 디자인용 더미데이터
                Movies = new ObservableCollection<MovieItem> {
                    new MovieItem { Title = "해리포터" },
                    new MovieItem { Title = "해리포터(3D)" },
                    new MovieItem { Title = "해리포터(4bit)" },
                    new MovieItem { Title = "해리포터(디지털)" }
                };
                EnableDates = new List<EnableDate> {
                    new EnableDate { Key="20100822", Value="08월 22일 금요일" }
                };
                Tickets = new ObservableCollection<TicketInfo> {
                    new TicketInfo { ViewStr = "1관 13 : 20" },
                    new TicketInfo { ViewStr = "1관 13 : 20" },
                    new TicketInfo { ViewStr = "1관 13 : 20" },
                    new TicketInfo { ViewStr = "1관 13 : 20" }
                };
                SelectedTheater = new TheaterItem { Name = "전대 씨너스" };
                #endregion
                //SelectedTheater = App.Current.Resources["SelectedTheater"] as TheaterItem;
                //getAllTicketingInfo();
            }
        }
        #endregion

        #region 전체 영화목록 및 극장목록 다운로드

        private void getAllTicketingInfo()
        {
            string url = "http://movie.naver.com/movie/reservation/ticketingInfo2.nhn";
            WebClient client = new WebClient();
            client.DownloadStringCompleted += AllTicketingInfoDownloaded;
            client.DownloadStringAsync(new Uri(url));
        }
        void AllTicketingInfoDownloaded(object sender, DownloadStringCompletedEventArgs e)
        {
            XDocument xdoc = XDocument.Parse(e.Result);
            allMovies = xdoc.Root.Element("movies").Descendants("item")
                .Select(item => new MovieItem
               {
                   Key = item.Attribute("key").Value,
                   Title = item.Value
               });

            string url = "http://movie.naver.com/movie/reservation/ticketingInfo2.nhn?theater=" + SelectedTheater.Key;
            WebClient client = new WebClient();
            client.DownloadStringCompleted += MovieListDownloadCompleted;
            client.DownloadStringAsync(new Uri(url));
        }
        void MovieListDownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            XDocument xdoc = XDocument.Parse(e.Result);

            var movies = xdoc.Root.Element("movies").Elements("item")
                .Select(item => item.Attribute("key").Value);

            Movies = allMovies.Where(item => movies.Contains(item.Key));
        }
        #endregion

        #region 상영날짜 다운로드
        private void getEnableDate(string movie)
        {
            string url = "http://movie.naver.com/movie/reservation/ticketingInfo2.nhn?theater=" + SelectedTheater.Key + "&movie=" + movie;
            WebClient client = new WebClient();
            client.DownloadStringCompleted += (sender, e) =>
            {
                XDocument xdoc = XDocument.Parse(e.Result);

                List<EnableDate> enableDates = null;
                XAttribute dateEnableAttr = xdoc.Root.Element("dates").Attribute("dateEnable");
                if (dateEnableAttr != null)
                {
                    MatchCollection matches = Regex.Matches(dateEnableAttr.Value, "([0-9]{4})([0-9]{2})([0-9]{2})");
                    enableDates = new List<EnableDate>();
                    EnableDate enableDate;
                    foreach (Match m in matches)
                    {
                        int year = Convert.ToInt32(m.Groups[1].Value);
                        int month = Convert.ToInt32(m.Groups[2].Value);
                        int day = Convert.ToInt32(m.Groups[3].Value);
                        DateTime date = new DateTime(year, month, day);
                        string week = "";
                        switch (date.DayOfWeek)
                        {
                            case DayOfWeek.Monday: week = "월요일"; break;
                            case DayOfWeek.Tuesday: week = "화요일"; break;
                            case DayOfWeek.Wednesday: week = "수요일"; break;
                            case DayOfWeek.Thursday: week = "목요일"; break;
                            case DayOfWeek.Friday: week = "금요일"; break;
                            case DayOfWeek.Saturday: week = "토요일"; break;
                            case DayOfWeek.Sunday: week = "일요일"; break;
                        }
                        enableDate = new EnableDate { Key = m.Value, Value = m.Groups[2].Value + "월 " + m.Groups[3].Value + "일 " + week };
                        enableDates.Add(enableDate);
                    }
                }
                EnableDates = enableDates;
            };
            client.DownloadStringAsync(new Uri(url));
        }
        #endregion

        #region 상영시간 다운로드
        private void getTime(string movie, string date)
        {
            string url = "http://movie.naver.com/movie/reservation/ticketingInfo2.nhn?movie=" + movie + "&theater=" + SelectedTheater.Key + "&date=" + date;
            WebClient client = new WebClient();
            client.DownloadStringCompleted += (sender, e) =>
            {
                XDocument xdoc = XDocument.Parse(e.Result);

                XElement tickets = xdoc.Root.Element("tickets");
                if (tickets != null)
                {
                    Tickets = tickets.Elements("info")
                        .Select(info =>
                        {
                            string str = Regex.Replace(info.Attribute("place").Value + info.Attribute("time").Value, "(.{1,3})(\\.?)([0-9]{2})([0-9]{2})", "$1 $3 : $4");
                            return new TicketInfo
                            {
                                ViewStr = str,
                                ID = info.Attribute("id").Value,
                                Time = info.Attribute("time").Value
                            };
                        });
                }
            };
            client.DownloadStringAsync(new Uri(url));
        }
        #endregion
    }
}